
package com.yuan.unit;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.widget.Toast;

/**
 * Toast工具类 会提高效率
 * 
 * @author YUAN
 */
public class ToastHelper {
    private static ToastHelper sInstance;
    private Toast mToast;

    public final static ToastHelper getInstance() {
        if (sInstance == null) {
            sInstance = new ToastHelper();

        }
        return sInstance;
    }

    private Toast getToast(Context context) {
        if (mToast != null) {
            mToast = new Toast(context);
        }
        return mToast;
    }

    public final void longToast(Context context, final String toast) {
        toast(context, toast, Toast.LENGTH_LONG);
    }

    public final void longToast(Context context, int id) {
        longToast(context, context.getString(id));
    }

    public final void shortToast(Context context, String toast) {
        toast(context, toast, Toast.LENGTH_SHORT);
    }

    public final void shortToast(Context context, int id) {
        shortToast(context, context.getString(id));
    }

    private final void toast(final Context context, final String toast,
            final int length) {
        if (Looper.getMainLooper() == Looper.myLooper()) {
            doShowToast(context, toast, length);
        } else {
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    doShowToast(context, toast, length);
                }
            });
        }
    }

    private final void doShowToast(Context context, String toast, int length) {
        try {
            final Toast t = getToast(context);
            t.setText(toast);
            t.setDuration(length);
            t.show();
        } catch (Exception e) {
            Toast.makeText(context, toast, length).show();
        }
    }

    public void onDestroy() {
        if (mToast != null) {
            mToast.cancel();
            mToast = null;
        }
        sInstance = null;
    }
}
